<script setup>
import {reactive, ref} from "vue";
import store from "@/store";
import router from "@/router";
import {ElMessage} from "element-plus";
import {axios} from '../../plugins/axios';

/*  data   */
const tabList = reactive(["密码登录", "免密登录"])
const tabSelected = ref(0)
const userForm = reactive({
  username: "",
  password: "",
})
const userFormError = reactive({
  username: "",
  password: "",
})
const userRules = reactive({
  username: [{
    required: true,
    message: "请输入用户名或手机",
    trigger: "blur"
  }],
  password: [{
    required: true,
    message: "请输入密码",
    trigger: "blur"
  }]
})
const smsForm = reactive({
  phone: "",
  code: ""
})
const smsRules = reactive({
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur"
    },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "手机号格式错误",
      trigger: "blur"
    },
  ],
  code: [{
    required: true,
    message: "请输入验证码",
    trigger: "blur"
  }]
})
const btnSmsTxt = ref("发送验证码")
const btnDisabled = ref(false);

const userFormRef = ref(null);
const smsFormRef = ref(null);

/*  函数   */
function changeTab(idx) {
  tabSelected.value = idx;
}
function userSubmitForm() {
  // 清空原有的错误信息,创建一个函数
  clearCustomFormError()
  console.log("submitForm函数开始执行");
  if (userFormRef.value) {
    console.log("表单引用有效，开始验证");
    userFormRef.value.validate((valid) => {
      console.log("验证结果:", valid);
      if (!valid) {
        console.log("验证未通过");
        return false;
      }
      console.log("验证通过");
      // 向后端发送axios请求
      axios.post("/base/auth/",userForm).then((res) => {
        // 根据返回值进行判断
        if (res.data.code === 0) {
          // 登录成功之后，写入cookie和state中，调用store/index的login方法
          store.commit('login',{username:res.data.data.username,token:res.data.data.token});
          router.push({path: "/"});
        } else if (res.data.code === 1000) {
          // 1000,字段错误，把相关错误信息放在标签中
          // 返回的错误信息格式:{username:['错误',],password:['错误',]},通过创建一个函数来解析数据validateFormFailed
          validateFormFailed(res.data.detail);
        } else if (res.data.code === 1001) {
          // 1001，校验错误，弹窗提示
          ElMessage.error(res.data.detail);
        } else {
          // 其他错误情况
          ElMessage.error("请求失败");
        }
      })
    })
  } else {
    console.log("表单引用无效或为空");
  }
}
function smsSubmitForm() {
  console.log("submitForm函数开始执行");
  if (smsFormRef.value) {
    console.log("表单引用有效，开始验证");
    smsFormRef.value.validate((valid) => {
      console.log("验证结果:", valid);
      if (!valid) {
        console.log("验证未通过");
        return false;
      }
      console.log("验证通过");
    })
  } else {
    console.log("表单引用无效或为空");
  }
}
function sendSmsCode(){
  smsFormRef.value.validateField("phone",(err, value) => {
    if (value) {
      return false;
    }
    // 验证通过之后进入发送验证码，以及限制流程
    btnDisabled.value = true;
    let txt=60;
    let interval=window.setInterval(function () {
      txt-=1;
      btnSmsTxt.value=`${txt}秒后重新发送`;
      if(txt<1){
        btnSmsTxt.value="重新发送";
        btnDisabled.value = false;
        window.clearInterval(interval);
      }
    },1000)
  })
}
function validateFormFailed(errorData) {
  for (let fieldName in errorData){
    let error=errorData[fieldName][0];
    userFormError[fieldName] = error;
  }
}
function clearCustomFormError(){
  for(let key in userFormError){
    userFormError[key]="";
  }
}


</script>

<template>
  <div class="main">
    <div class="loginBox">
      <div class="tabBoxSwitch">
        <div class="tabBoxSwitchUl">
          <li :class="tabSelected===index?'tab-active':''" v-for="(txt,index) in tabList" :key="index"
              @click="changeTab(index)">{{ txt }}
          </li>
        </div>
      </div>
      <div v-show="tabSelected===0">
        <el-form :model="userForm" :rules="userRules" ref="userFormRef">
          <el-form-item style="margin-top: 20px" prop="username" :error="userFormError.username">
            <el-input v-model="userForm.username" placeholder="用户名或手机号"></el-input>
          </el-form-item>
          <el-form-item prop="password" :error="userFormError.password">
            <el-input v-model="userForm.password" placeholder="密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="userSubmitForm()" type="primary" size="small">登 录</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="tabSelected===1">
        <el-form :model="smsForm" :rules="smsRules" ref="smsFormRef">
          <el-form-item style="margin-top: 20px" prop="phone">
            <el-input v-model="smsForm.phone" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item style="width: 100%;" prop="code">
            <el-row :gutter="10" style="width: 100%;">
              <el-col :span="16">
                <el-input v-model="smsForm.code" placeholder="验证码"></el-input>
              </el-col>
              <el-col :span="8">
                <el-button :disabled="btnDisabled" style="width: 100%;" @click="sendSmsCode">{{ btnSmsTxt }}</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button @click="smsSubmitForm()" type="primary" size="small">登 录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.main {
  width: 100%;
  height: 100vh;
  background-color: #2e3e9c;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loginBox {
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(26, 26, 26, 0.1);
  width: 380px;
  min-height: 200px;
  padding: 0 24px 20px;
}

.tabBoxSwitch .tabBoxSwitchUl {
  list-style: none;
  padding: 0;
  margin: 0;
}

.tabBoxSwitch .tabBoxSwitchUl li {
  display: inline-block;
  height: 60px;
  font-size: 16px;
  line-height: 60px;
  margin-right: 24px;
  cursor: pointer;
}

.tab-active {
  position: relative;
  color: #1a1a1a;
  font-weight: 600;
  font-synthesis: style;
}

.tab-active::before {
  display: block;
  position: absolute;
  bottom: 0;
  content: "";
  width: 100%;
  height: 3px;
  background-color: #0084ff;
}
</style>